<template>
  <div>
    <el-upload
      class="flex"
      accept="jpg,jpeg,png"
      :action="props.action"
      :headers="{ Authorization: token }"
      :show-file-list="false"
      :before-upload="beforeUpload"
      :on-success="success"
      :preview-src-list="[image]"
      :style="{
        width: props.width + 'px',
        height: props.height + 'px',
        overflow: 'hidden',
      }"
    >
      <el-image
        v-if="image"
        class="rounded"
        :src="image"
        :style="{
          width: props.width + 'px',
          height: props.height + 'px',
          overflow: 'hidden',
        }"
      />
      <el-icon
        v-else
        class="border rounded"
        :style="{
          width: props.width + 'px',
          height: props.height + 'px',
          fontSize: '2rem',
        }"
      >
        <Plus />
      </el-icon>
    </el-upload>
  </div>
</template>

<script setup>
import { local } from '@/utils/storage'

const token = local.get('admin-token') ? `Bearer ${local.get('admin-token')}` : ''
const props = defineProps({
  action: '/demo/upload',
  width: 240,
  height: 120,
})
const image = ref('')
const emits = defineEmits(['update:value'])
onMounted(() => {
  const attrs = useAttrs()
  if (attrs.value) {
    image.value = attrs.value
  }
})

const beforeUpload = file => {
  const sufix = file.name.split('.')[1] || ''
  if (!['jpg', 'jpeg', 'png'].includes(sufix)) {
    ElMessage.error('请上传 jpg、jpeg、png 格式的图片')
    return false
  }
}
// 上传成功后, 更新字段的值
const success = e => {
  image.value = e.data
  emits('update:value', image.value)
}
</script>

<style lang="scss" scoped></style>
